%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

extern char buf[];
extern char *myptr;
extern char *mylim;
extern char *argvbuf[];
extern int argcnt;

#undef  YY_INPUT
#define YY_INPUT(b, r, ms) (r = my_yyinput(b, ms))

int my_yyinput(char *buf, int max);
void add_arg(const char *arg);

%}

%x      QUOTE
%x      SINGQUOTE
blank   [ \t]

%%

"\""            {BEGIN QUOTE;}
<QUOTE>[^\n"]+  {add_arg(yytext);}
<QUOTE>"\""     {BEGIN 0;}
<QUOTE>\n       {BEGIN 0;}
";"             {add_arg(yytext);}
">"             {add_arg(yytext);}
"<"             {add_arg(yytext);}
"|"             {add_arg(yytext);}
"&"             {add_arg(yytext);}
[^ \t\n|&<>;"]+  {add_arg(yytext);}
.               ;

%%

void add_arg(const char *arg)
{
    int len = strlen(arg);

    argvbuf[argcnt] = (char *)malloc(len+1);
    strncpy(argvbuf[argcnt], arg, len+1);
    argcnt ++;
    argvbuf[argcnt] = 0;
}

int my_yyinput(char *buf, int max)
{
    int n;

    n = (max < (mylim-myptr)) ? max : (mylim-myptr);
    if (n > 0) {
        memcpy(buf, myptr, n);
        myptr += n;
    }

    return n;
}
